package com.car.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.car.entity.Image;
import com.car.entity.User;
import com.car.service.ImageService;
import com.car.service.UserService;
import com.car.util.SUKUtil;
import com.car.util.getFile;
import com.car.validation.Base64Util;
import com.car.validation.FileUtil;
import com.car.validation.HttpUtil;
import com.car.word.WordResult;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;
import javax.sound.sampled.Port;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/users")
public class UserController {
	@Autowired
	UserService userService;

	@Autowired
	ImageService imageService;

	Map<String, Object> maps = new HashMap<String, Object>();
	
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	@Value("${server.port}")
	String port;

	@CrossOrigin  //解决跨域
	@RequestMapping("/h5Logins")
	@ResponseBody
	public Map<String, Object> loginsH5(@RequestParam("phone") String phone, @RequestParam("userPwd") String userPwd,
			HttpSession session) {
			System.out.println(port);
			logger.info("执行查询....");
		User user = userService.logins(phone,userPwd);
		maps.put("msg", user != null ? true : false);
		session.setAttribute("loginSuccess", user);
		return maps;

	}

	/**
	 * 注册 @Title: H5registered @Description: TODO(这里用一句话描述这个方法的作用) @param @param
	 * phone @param @param userName @param @param userPwd @param @return
	 * 参数 @return Map<String,Object> 返回类型 @throws
	 */
	@RequestMapping("/H5registered")
	@ResponseBody
	public Map<String, Object> registerH5(@RequestParam("phone") String phone,
			@RequestParam("userName") String userName, @RequestParam("userPwd") String userPwd) {

		User user = new User();
		user.setPhone(phone);
		user.setUserName(userName);
		user.setUserPwd(userPwd);
		int nums = userService.h5register(user);
		maps.put("msg", nums > 0 ? true : false);
		return maps;
	}

	/**
	 * 身份 @Title: H5ShenCid @Description: TODO(这里用一句话描述这个方法的作用) @param @param
	 * articleFiles @param @param articleFile @param @param
	 * userName @param @param userCid @param @param zhengUrl @param @param
	 * session @param @return 参数 @return Map<String,Object> 返回类型 @throws
	 */
	@RequestMapping("/H5ShenCid")
	@ResponseBody
	public Map<String, Object> shenFen(MultipartFile articleFiles, MultipartFile articleFile, String userName,
			String userCid, String zhengUrl, HttpSession session) {
		User user = (User) session.getAttribute("loginSuccess");
		String fanNames = articleFiles.getOriginalFilename();
		String zhengNames = articleFile.getOriginalFilename();

		File fileLinShi = new File("E:/Y2/car/carRental/car-Web/src/main/resources/static/fei/" + zhengNames);
		File fileLinShifu = new File("E:/Y2/car/carRental/car-Web/src/main/resources/static/fei/" + fanNames);
		String accessToken = "24.67812640c663b880cb82d0798e9843a8.2592000.1545377377.282335-14892635";
		String params = null;
		try {
			articleFile.transferTo(fileLinShi);
			articleFiles.transferTo(fileLinShifu);
			// 身份证识别url
			String idcardIdentificate = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard";
			// 本地图片路径
			byte[] imgData = FileUtil.readFileByBytes(fileLinShi.toString());
			String imgStr = Base64Util.encode(imgData);
			// 识别身份证正面id_card_side=front;识别身份证背面id_card_side=back;
			params = "id_card_side=front&" + URLEncoder.encode("image", "UTF-8") + "="
					+ URLEncoder.encode(imgStr, "UTF-8");
			/**
			 * 线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
			 */
			String result = HttpUtil.post(idcardIdentificate, accessToken, params);
			JSONObject jsStr = JSONObject.parseObject(result);
			String wordsResults = jsStr.getString("words_result");
			JSONObject jsStr1 = JSONObject.parseObject(wordsResults);
			WordResult wr = (WordResult) JSONObject.toJavaObject(jsStr1, WordResult.class);

			String userNames = wr.get姓名().getWords();
			String CitiNumber = wr.get公民身份号码().getWords();
			if (userNames.equals("") || CitiNumber.equals("")) {
				maps.put("msg", 2);// 身份证图不正确
				fileLinShi.delete();
				fileLinShifu.delete();
				return maps;
			}
			if (userNames.equals(userName) && userCid.equals(CitiNumber)) {
				imgData = FileUtil.readFileByBytes(fileLinShifu.toString());
				imgStr = Base64Util.encode(imgData);
				params = "id_card_side=back&" + URLEncoder.encode("image", "UTF-8") + "="
						+ URLEncoder.encode(imgStr, "UTF-8");
				String results = HttpUtil.post(idcardIdentificate, accessToken, params);
				jsStr = JSONObject.parseObject(results);

				wordsResults = jsStr.getString("words_result");
				jsStr1 = JSONObject.parseObject(wordsResults);
				wr = (WordResult) JSONObject.toJavaObject(jsStr1, WordResult.class);

				String ExpiryDate = wr.get失效日期().getWords();
				String issue = wr.get签发机关().getWords();
				if (ExpiryDate.equals("") || issue.equals("")) {
					maps.put("msg", 1);
					fileLinShi.delete();
					fileLinShifu.delete();
					return maps;
				}
				user.setRealName(userNames);
				user.setIdCard(userCid);
				Image image = new Image();
				ArrayList<String> list = getFile.getfiles("E:/Y2/car/carRental/car-Web/src/main/webapp/WEB-INF/image/",
						0);
				String zhengNames1 = zhengNames;
				String fanNames1 = fanNames;
				zhengNames1 = getFile.checkFileName(list, zhengNames1, 0);
				fanNames1 = getFile.checkFileName(list, fanNames1, 0);
				image.setFrontFaceOfId(zhengNames1);
				image.setReverseSideOfId(fanNames1);
				if (fileLinShi.renameTo(
						new File("E:/Y2/car/carRental/car-Web/src/main/webapp/WEB-INF/image/" + zhengNames1))) {
					if (fileLinShifu.renameTo(
							new File("E:/Y2/car/carRental/car-Web/src/main/webapp/WEB-INF/image/" + fanNames1))) {
						int nums = userService.updUserInfo(user, image);
						maps.put("msg", nums > 0 ? true : false);
					}
				} else {
					System.out.println("失败！");
				}
			} else {
				maps.put("msg", false);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return maps;
	}

	/**
	 * 
	    * @Title: H5jiaZhao
	    * @Description: TODO(这里用一句话描述这个方法的作用)
	    * @param @param articleFiles
	    * @param @param articleFile
	    * @param @param session
	    * @param @return    参数
	    * @return Map<String,Object>    返回类型
	    * @throws
	 */
	@RequestMapping("/H5jiaZhao")
	@ResponseBody
	public Map<String, Object> jiaZhao(MultipartFile articleFiles, MultipartFile articleFile, HttpSession session) {
		User user = (User) session.getAttribute("loginSuccess");
		String fanNames = articleFiles.getOriginalFilename();
		String zhengNames = articleFile.getOriginalFilename();

		File fileLinShi = new File("E:/Y2/car/carRental/car-Web/src/main/resources/static/fei/" + zhengNames);
		File fileLinShifu = new File("E:/Y2/car/carRental/car-Web/src/main/resources/static/fei/" + fanNames);
		String accessToken = "24.67812640c663b880cb82d0798e9843a8.2592000.1545377377.282335-14892635";
		String params = null;
		try {
			articleFile.transferTo(fileLinShi);
			articleFiles.transferTo(fileLinShifu);
			// 驾驶证识别url
			String idcardIdentificate = "https://aip.baidubce.com/rest/2.0/ocr/v1/driving_license";
			// 本地图片路径
			byte[] imgData = FileUtil.readFileByBytes(fileLinShi.toString());
			String imgStr = Base64Util.encode(imgData);
			// 识别身份证正面id_card_side=front;识别身份证背面id_card_side=back;
			params = "id_card_side=front&" + URLEncoder.encode("image", "UTF-8") + "="
					+ URLEncoder.encode(imgStr, "UTF-8");
			/**
			 * 线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
			 */
			String result = HttpUtil.post(idcardIdentificate, accessToken, params);
			JSONObject jsStr = JSONObject.parseObject(result);
			String wordsResults = jsStr.getString("words_result");
			System.out.println(wordsResults);
			JSONObject jsStr1 = JSONObject.parseObject(wordsResults);
			WordResult wr = (WordResult) JSONObject.toJavaObject(jsStr1, WordResult.class);
			String validTerm = wr.get有效期限().getWords();
			String userName = wr.get姓名().getWords();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
			Date dateStart = sdf.parse(wr.get有效起始日期().getWords());
			if (validTerm != "" && dateStart != null) {
				Calendar c = Calendar.getInstance();
				c.setTime(dateStart);
				int nian = c.get(Calendar.YEAR);
				/*char validnian = validTerm.charAt(0);*/
				Integer sr  = Integer.parseInt(validTerm.substring(0,validTerm.indexOf("年"))) ;
				/*int ss = validnian - '0';*/
				Calendar cl = Calendar.getInstance();
				int years = cl.get(Calendar.YEAR);
				if (years > (nian + sr)) {
					maps.put("msg", "1");// 已过期
					fileLinShi.delete();
					fileLinShifu.delete();
					return maps;
				}

				imgData = FileUtil.readFileByBytes(fileLinShifu.toString());
				imgStr = Base64Util.encode(imgData);
				params = "id_card_side=back&" + URLEncoder.encode("image", "UTF-8") + "="
						+ URLEncoder.encode(imgStr, "UTF-8");
				String results = HttpUtil.post(idcardIdentificate, accessToken, params);
				jsStr = JSONObject.parseObject(results);
				wordsResults = jsStr.getString("words_result");
				jsStr1 = JSONObject.parseObject(wordsResults);
				wr = (WordResult) JSONObject.toJavaObject(jsStr1, WordResult.class);
				String fileNumber = wr.get姓名().getWords();
				if (!fileNumber.equals(userName)) {
					maps.put("msg", "2");// 身份信息不统一
					fileLinShi.delete();
					fileLinShifu.delete();
					return maps;
				}
			}
			ArrayList<String> list = getFile.getfiles("E:/Y2/car/carRental/car-Web/src/main/webapp/WEB-INF/image/", 0);
			String zhengNames1 = zhengNames;
			String fanNames1 = fanNames;
			zhengNames1 = getFile.checkFileName(list, zhengNames1, 0);
			fanNames1 = getFile.checkFileName(list, fanNames1, 0);
			Image image = new Image();
			image.setTheDriverPositive(zhengNames1);
			image.setDriverlicenseOpposite(fanNames1);
			image.setPhotoId(user.getIdCardImage());
			if (fileLinShi
					.renameTo(new File("E:/Y2/car/carRental/car-Web/src/main/webapp/WEB-INF/image/" + zhengNames1))) {
				if (fileLinShifu
						.renameTo(new File("E:/Y2/car/carRental/car-Web/src/main/webapp/WEB-INF/image/" + fanNames1))) {

					int nums = imageService.updateByPrimaryKey(image);
					maps.put("msg", nums > 0 ? "success" : "erro");
				}
			} else {
				System.out.println("失败！");
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return maps;
	}

	/**
	 * 密码修改跳转 @Title: passwords @Description: TODO(这里用一句话描述这个方法的作用) @param @return
	 * 参数 @return String 返回类型 @throws
	 */
	@RequestMapping({ "/passwords", "" })
	public String pasword(HttpSession session,Model model) {
		User user =(User)session.getAttribute("loginSuccess");
			model.addAttribute("userPwd", user!=null?user.getUserPwd():"error");
		return "H5phone/password";
	}
	/**
	 * 密码修改功能
	    * @Title: passwordUpd
	    * @Description: TODO(这里用一句话描述这个方法的作用)
	    * @param @return    参数
	    * @return Map<String,Object>    返回类型
	    * @throws
	 */
	@RequestMapping("/pwdUpd")
	@ResponseBody
	public Map<String, Object> passwordUpd(@RequestParam("userPwd")String userPwd,HttpSession session){
		User user =(User)session.getAttribute("loginSuccess");
		int nums = userService.updUserPwd(userPwd, user.getUserId());
		maps.put("msg", nums>0?true:false);
		return maps;
	}

	/**
	 * 联系方式
	    * @Title: conta
	    * @Description: TODO(这里用一句话描述这个方法的作用)
	    * @param @return    参数
	    * @return String    返回类型
	    * @throws
	 */
	@RequestMapping({"/contacts",""})
	public String conta(HttpSession session,Model model){
		User user = (User) session.getAttribute("loginSuccess");
		if(user==null){
			model.addAttribute("error", "1");
		}else{
		User list = userService.selectByPrimaryKey(user.getUserId());
		String phone = list.getPhone();
		String phoneNumber = phone.substring(0, 3)+"****"+phone.substring(7,phone.length());
		model.addAttribute("phone", phoneNumber);
		model.addAttribute("userInfos", list);
		}
		return "H5phone/contact";
	}
	/**
	 * 紧急联系人，电话
	    * @Title: infosSaves
	    * @Description: TODO(这里用一句话描述这个方法的作用)
	    * @param @return    参数
	    * @return Map<String,Object>    返回类型
	    * @throws
	 */
	@RequestMapping({"/infosSave"})
	@ResponseBody
	public Map<String, Object> infosSaves(@RequestParam("emergencyContacts")String emergencyContacts,
			@RequestParam("contactNumber")String contactNumber,HttpSession session){
		User user = (User)session.getAttribute("loginSuccess");
		int nums = userService.updUsersTojinji(emergencyContacts, contactNumber, user.getUserId());
		maps.put("msg", nums>0?true:false);
		return maps;
	}
	
	/**
	 * 邮箱修改
	    * @Title: emails
	    * @Description: TODO(这里用一句话描述这个方法的作用)
	    * @param @return    参数
	    * @return String    返回类型
	    * @throws
	 */
	@RequestMapping({"/emails",""})
	public String emails(HttpSession session,Model model){
		User user = (User)session.getAttribute("loginSuccess");
		User users =userService.selectByPrimaryKey(user.getUserId());
		model.addAttribute("userEmail", users);
		return "H5phone/email";
	}
	/**
	 * 保存邮箱
	    * @Title: emialSaves
	    * @Description: TODO(这里用一句话描述这个方法的作用)
	    * @param @param email
	    * @param @param session
	    * @param @return    参数
	    * @return Map<String,Object>    返回类型
	    * @throws
	 */
	@RequestMapping({"/emailSave",""})
	@ResponseBody
	public Map<String, Object>emialSaves(String email,HttpSession session){
		User user = (User)session.getAttribute("loginSuccess");
		int nums = userService.updUsersEmail(email, user.getUserId());
		maps.put("msg", nums>0?true:false);
		return maps;
	}

}